<?php

// $Id$

require_once($WSC->get_site_inc_dir().'modules/tree_menu/tree_menu_html_gatherer.class.php');
require_once('tree_menu_ml_dbc.class.php');
require_once('tree_menu_ml_dbc_file_importer.class.php');

class Tree_Menu_ML_Preparer extends Tangra_Class {
	public static function prepare_menu(DB_Connection $dbc, $db_tables_prefix, $menu_css_id, $menu_tpl_file, $cache_dir, $import_dir, $lang, $lang_arr) {
		$menu_db_table = $db_tables_prefix.'menu';

		$cache_dir = tangra_normalize_path($cache_dir);
		$import_dir = tangra_normalize_path($import_dir);

		if (file_exists($cache_dir.'regenerate')) {
			$html = Tree_Menu_ML_Preparer::generate_menu($dbc, $db_tables_prefix, $menu_css_id, $cache_dir, $menu_tpl_file, $import_dir, $lang, $lang_arr);
			unlink($cache_dir.'regenerate');
		} else {
			if (file_exists($cache_dir.'menu_'.$lang.'.html')) {
				$html = file_get_contents($cache_dir.'menu_'.$lang.'.html');
			} else {
				$html = Tree_Menu_ML_Preparer::generate_menu($dbc, $db_tables_prefix, $menu_css_id, $cache_dir, $menu_tpl_file, $import_dir, $lang, $lang_arr);
			}
		}

		return $html;
	}


	public static function generate_menu(DB_Connection $dbc, $db_tables_prefix, $menu_css_id, $menu_dir, $menu_template_file, $import_dir, $lang, $lang_arr) {
		$menu_db_table = $db_tables_prefix.'menu';

		$menu_dir = tangra_normalize_path($menu_dir);
		$menu_db_table = addslashes($menu_db_table);

		$menu = new Tree_Menu_ML_DBC($menu_db_table, $lang);

		$menu->load_menu($dbc, true);

		$import_dir = $menu_dir.'import/';
		if (!is_dir_empty($import_dir)) {
			$importer = new Tree_Menu_ML_DBC_File_Importer();

			$rez = $importer->import($dbc, $menu, $import_dir, true, $db_tables_prefix, $lang, $lang_arr);

			Tree_Menu_ML_Preparer::remove_imported_files($import_dir, $rez['files']);
		}

		// Reloading so all items are ordered
		$menu = new Tree_Menu_ML_DBC($menu_db_table, $lang);
		$menu->load_menu($dbc, true);

		$tmhg = new Tree_Menu_HTML_Gatherer();
		$tple = new Tple();
		$html = $tmhg->get_html($tple, $menu_template_file, $menu, $menu_css_id);

		file_put_contents($menu_dir.'menu_'.$lang.'.html', $html);

		return $html;
	}


	public static function remove_imported_files($import_dir, $files) {
		tangra_normalize_path($import_dir);

		foreach($files as $file) {
			if (file_exists($import_dir.$file)) {
				unlink($import_dir.$file);
			}
		}
	}
}